#include <am.h>
#include <x86.h>

#define RTC_PORT 0x48   // Note that this is not standard
#define I8042_DATA_PORT 0x60
#define I8042_STATUS_PORT 0x64
static unsigned long boot_time;

void _ioe_init() {
  boot_time = inl(RTC_PORT);
}

unsigned long _uptime() {
  return inl(RTC_PORT) - boot_time;
}

uint32_t* const fb = (uint32_t *)0x40000;

_Screen _screen = {
  .width  = 400,
  .height = 300,
};

extern void* memcpy(void *, const void *, int);

void _draw_rect(const uint32_t *pixels, int x, int y, int w, int h) {
  for (int i = 0; i < h; i++) {
      int current_y = y + i;
      if (current_y < 0 || current_y >= _screen.height) continue;
      uint32_t *dest = fb + current_y * _screen.width + x;
      const uint32_t *src = pixels + i * w;
      int copy_w = w;

      // 如果起始x超出左边界，调整复制的起点和宽度
      if (x < 0) {
          copy_w += x;  // x为负，copy_w减少|x|个像素
          src -= x;     // 源数据跳过前|x|个像素
          dest -= x;    // 目标地址对齐到屏幕左边界
          x = 0;        // 重置当前行的x为0
      }
      // 如果当前行宽度超出右边界，调整复制的宽度
      if (x + copy_w > _screen.width) {
          copy_w = _screen.width - x;
      }
      // 若调整后无需复制跳过
      if (copy_w <= 0) continue;

      memcpy(dest, src, copy_w * sizeof(uint32_t));
  }
}

void _draw_sync() {
}

int _read_key() {
  return (inb(0x64) & 0x1) ? inl(0x60) : (uint32_t)_KEY_NONE;
}

